﻿Public MustInherit Class PersistenceServiceImpl(Of T As Base, M As Manager(Of T))
    Inherits ServiceImpl(Of PersistenceListener(Of T))
    Implements PersistenceService(Of T)

    Protected manager As M

    Public Sub New(ByRef manager As M)
        Me.manager = manager
    End Sub

    Public Sub delete(ByRef entity As T) Implements PersistenceService(Of T).delete
        addFireBlock()
        Connection.open()
        Try
            beforeDelete(entity)
        Catch exception As Exception
            showError(exception.Message)
            Exit Sub
        End Try
        manager.delete(entity)
        Connection.close()
        removeFireBlock()
        fireDeleted(entity)
    End Sub

    Public Function findAll() As System.Collections.Generic.List(Of T) Implements PersistenceService(Of T).findAll
        Connection.open()
        Dim results As List(Of T) = manager.findAll()
        For Each result As T In results
            fillUp(result)
        Next
        Connection.close()
        Return results
    End Function

    Public Function findById(ByRef entity As T) As T Implements PersistenceService(Of T).findById
        Connection.open()
        Dim result As T = manager.findById(entity)
        Connection.close()
        Return result
    End Function

    Public Sub save(ByRef entity As T) Implements PersistenceService(Of T).save
        addFireBlock()
        Connection.open()
        Try
            beforeSave(entity)
        Catch exception As Exception
            showError(exception.Message)
            Exit Sub
        End Try
        manager.save(entity)
        Connection.close()
        removeFireBlock()
        fireSaved(entity)
    End Sub

    Protected MustOverride Sub fillUp(ByRef entity As T)

    Protected MustOverride Sub beforeDelete(ByRef entity As T)

    Protected MustOverride Sub beforeSave(ByRef entity As T)

    ' fire
    Protected Sub fireDeleted(ByRef entity As T)
        If SharedCounter.getPersistenceServiceInstance().getValue = 0 Then
            For Each listener As PersistenceListener(Of T) In getObservable.getListeners
                listener.onDeleted(entity)
            Next
        End If
    End Sub

    Protected Sub fireSaved(ByRef entity As T)
        If SharedCounter.getPersistenceServiceInstance().getValue = 0 Then
            For Each listener As PersistenceListener(Of T) In getObservable().getListeners()
                listener.onSaved(entity)
            Next
        End If
    End Sub

    Protected Sub addFireBlock()
        SharedCounter.getPersistenceServiceInstance().increment()
    End Sub

    Protected Sub removeFireBlock()
        SharedCounter.getPersistenceServiceInstance().decrement()
    End Sub

    Private Sub showError(ByVal message As String)
        MsgBox(message, MsgBoxStyle.Critical, "Datenbank Fehler")
    End Sub


End Class
